package com.platform.template.redis;

import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

/**
 * <pre>
 * 功能：
 * </pre>
 * @author wei.gao
 */
public class JsonStringRedisSerializer implements RedisSerializer<Object> {
    private final StringRedisSerializer stringRedisSerializer;

    public JsonStringRedisSerializer() {
        this(new StringRedisSerializer());
    }

    public JsonStringRedisSerializer(StringRedisSerializer stringSerializer) {
        this.stringRedisSerializer = stringSerializer;
    }

    @Override
    public byte[] serialize(Object o) throws SerializationException {
    	if(o == null) return new byte[0];
        String jsonString = JSON.toJSONString(o, SerializerFeature.WriteClassName);
        return this.stringRedisSerializer.serialize(jsonString);
    }

    @Override
    public Object deserialize(byte[] bytes) throws SerializationException {
    	if(bytes == null) return null;
        String objectInString = this.stringRedisSerializer.deserialize(bytes);
        return JSON.parse(objectInString);
    }
}
